<!-- 职位类别 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew
        title="职位类别"
        :breadCrumb="['组织', '基础设置', '职位类别']"
        :isShowBtn="true"
        show-back
      >
      </PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space>
          <span>职位类别({{ flatData.length }})</span>
          <span>|</span>
          <div>
            <a-dropdown
              :popup-max-height="false"
              v-model="treeLevel"
              @select="(e)=> handleTreeLevelSelect(e as number)"
            >
              <span style="cursor: pointer">
                展开{{ treeLevel }}级<icon-down style="color: #165dff" />
              </span>
              <template #content>
                <a-doption :value="1">1级</a-doption>
                <a-doption :value="2">2级</a-doption>
                <a-doption :value="3">3级</a-doption>
              </template>
            </a-dropdown>
          </div>
        </a-space>
      </template>
      <template #right>
        <a-button type="primary" @click="showModals">新增职位类别</a-button>
        <a-button type="outline" @click="remove(null)" status="danger"
          >批量删除</a-button
        >
      </template>
    </ConditionBox>
    <TableTurn
      ref="tableRef"
      :tableData="getSortData"
      :isShowPagination="false"
      :args="args"
    >
      <template>
        <a-table-column :width="150" align="left">
          <template #title>
            <div
              style="
                position: absolute;
                transform: translate(0, -50%);
                left: 32px;
              "
            >
              职位类别
            </div>
          </template>
          <template #cell="{ record }">
            <div
              :style="{
                textAlign: 'left',
                paddingLeft:
                  record.level > 2 ? '32px' : (record.level - 1) * 16 + 'px'
              }"
            >
              {{ record.name }}
            </div>
          </template>
        </a-table-column>
        <a-table-column
          title="职位类别编码"
          data-index="code"
          :width="100"
        ></a-table-column>
        <a-table-column
          title="描述"
          :width="300"
          data-index="remark"
        ></a-table-column>
        <a-table-column title="是否启用" data-index="isEnable" :width="100">
          <template #cell="{ record }">
            <a-tag
              class="enable"
              :color="
                record.isEnable === 1
                  ? `rgb(var(--green-1))`
                  : 'rgb(var(--danger-1))'
              "
              :style="{
                color:
                  record.isEnable === 1
                    ? `rgb(var(--green-6))`
                    : 'rgb(var(--danger-6))',
                '--enable':
                  record.isEnable === 1
                    ? `rgb(var(--green-6))`
                    : 'rgb(var(--danger-6))'
              }"
            >
              {{ record.isEnable === 1 ? '启用' : '停用' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="操作" :width="100" fixed="right" align="left">
          <template #cell="{ record }">
            <a-space class="icon" :size="0">
              <div v-if="record.pid === 0" @click="sonAdd(record, '新增序列')">
                <a-tooltip content="新增序列">
                  <icon-font type="icon-add-def" :size="26"></icon-font>
                </a-tooltip>
              </div>
              <div
                v-if="record.son === 1"
                @click="sonAdd(record, '新增子序列')"
              >
                <a-tooltip content="新增子序列">
                  <icon-font type="icon-add-def" :size="26"></icon-font>
                </a-tooltip>
              </div>
              <div
                @click="goDetail(record.id, record.name)"
                v-if="!record.children"
              >
                <a-tooltip content="模板设置">
                  <icon-font type="icon-setting-def" :size="26"></icon-font>
                </a-tooltip>
              </div>
              <div @click="edit(record)">
                <a-tooltip content="编辑">
                  <icon-font type="icon-edit" :size="26"></icon-font>
                </a-tooltip>
              </div>
              <div>
                <a-tooltip content="删除" position="left">
                  <a-popconfirm
                    content="确定删除吗?"
                    position="left"
                    @ok="remove(record.id)"
                  >
                    <icon-font type="icon-delete" :size="26"></icon-font>
                  </a-popconfirm>
                </a-tooltip>
              </div>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </TableTurn>
  </ContentCard>
  <!-- <Modals
    :refresh="refresh"
    :visible="modalVisible"
    :oldData="editData"
    :onChangeVisible="isshowModals"
    :onOpenRefresh="openRefresh"
    :uniqueCode="uniqueCode"
    :title="currModalTitle"
    :status="currStatus"
  ></Modals> -->
  <Modals
    v-model:visible="modalVisible"
    :data="editData"
    :title="currModalTitle"
    :status="currStatus"
    @typeEmit="typeEmit"
  />
</template>
<script lang="ts" setup>
import { flatTree, dataTreeFilter } from '@/utils/utils';
import Modals from './Modal.vue';
import { Modal } from '@arco-design/web-vue';
import { Message } from '@arco-design/web-vue';
import {
  getPositionSortList,
  delPositionSortList,
  addPositionSortList,
  setPositionSortList,
  CheckPositionSortList
} from '@/apis/management/organization/baseSetting/PositionSystem/index';
import { cloneDeep } from 'lodash';
import '../../../../../../style.css';
const tableRef = ref();
const uniqueCode: string[] = reactive([]);
const router = useRouter();
const editData = ref({});

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  stripe: true,
  indentSize: 0
});
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
let treeLevel = ref(3); // 展开多少层子树，初始展开1层
let currModalTitle = ref('新增职位类别');
let currStatus = ref('add'); // 模态框状态 add 新增 edit编辑
// 选择展开子树层级事件
const handleTreeLevelSelect = (val: number) => {
  treeLevel.value = val;
};

// 处理数据展开层级
const handleLevel = () => {
  tableRef.value.currExpandedKeys = [];
  flatData.value.forEach((item: any) => {
    if (item.level < treeLevel.value)
      tableRef.value.currExpandedKeys.push(item.id);
  });
};

watch(
  () => treeLevel.value,
  (val) => {
    handleLevel();
  }
);

// 删除
const remove = async (id: number) => {
  // await delPositionSortList({
  //   id
  // });
  tableRef.value.loadData();
  if (!id) {
    if (selectedList.value.length === 0) {
      Message.error('请至少选择一项！');
    } else {
      Modal.confirm({
        title: '提示',
        content: '确定要删除选中的数据吗？',
        onOk: async () => {
          try {
            await delPositionSortList({
              ids: selectedList.value
            });
            tableRef.value.selectedList = [];
            tableRef.value.loadData();
          } catch (error: unknown) {
            console.log(error);
          }
        }
      });
    }
  } else {
    await delPositionSortList({
      ids: [id]
    });
    tableRef.value.selectedList = [];
    tableRef.value.loadData();
  }
};

// 模板设置
const goDetail = (id: number, name: string) => {
  console.log('id', id);
  router.push({
    name: 'PositionSettingTemplate',
    query: { userId: id, name }
  });
};
// 编辑
const edit = (data: any) => {
  editData.value = { ...data };
  if (editData.value.level === 1) {
    currModalTitle.value = '编辑职位类别';
  } else if (editData.value.level === 2) {
    currModalTitle.value = '编辑序列';
  } else if (editData.value.level === 3) {
    currModalTitle.value = '编辑子序列';
  }
  currStatus.value = 'edit';
  console.log('=================editData===================');
  console.log(editData.value);
  console.log('====================================');
  modalVisible.value = true;
};
// 开启刷新
const openRefresh = (e: boolean) => {
  refresh.value = e;
  if (tableRef.value) {
    tableRef.value.loadData();
    refresh.value = false;
    modalVisible.value = false;
  }
};

const modalVisible = ref(false); // 判断是否显示弹出框
// 关闭弹窗
const isshowModals = (e: boolean) => {
  editData.value = {};
  modalVisible.value = e;
};

// 新增弹窗
const showModals = () => {
  currModalTitle.value = '新增职位类别';
  currStatus.value = 'add';
  editData.value = null;
  modalVisible.value = true;
};
// 子序列新增
const sonAdd = (data: any, title: string) => {
  editData.value = cloneDeep(data);
  editData.value.remark = '';
  editData.value.isEnable = 1;
  editData.value.code = '';
  currModalTitle.value = title;
  currStatus.value = 'add';
  modalVisible.value = true;
};
// 刷新数据
const refresh = ref(false);
let flatData = ref<any>([]);
const disposeData = (arr: any[]) => {
  // 默认只有最多三层数据
  arr.forEach((ele: any) => {
    uniqueCode.push(ele.code);
    ele.level = 1;
    ele.upstage = 1;
    ele.typeName = ele.name;
    if (!ele.children) return;
    if (ele.children) {
      ele.children.forEach((eles: any) => {
        eles.level = 2;
        uniqueCode.push(eles.code);
        if (eles.children) {
          eles.children.forEach((eless: any) => {
            eless.level = 3;
            uniqueCode.push(eless.code);
            eless.typeName = ele.name;
            eless.sequenceName = eles.name;
            eless.subSequenceName = eless.name;
            // eless.topLevel = ele.name;
            // eless.top = eles.name;
          });
        }
        eles.son = 1;
        eles.typeName = ele.name;
        eles.sequenceName = eles.name;
        // eles.topLevel = ele.name;
      });
    }
  });
  return arr;
};

const getSortData = async () => {
  try {
    const res: any = await getPositionSortList();
    disposeData(res.positionCategoryList);
    flatData.value = flatTree(disposeData(res.positionCategoryList));
    console.log(
      '🚀 ~ file: index.vue:259 ~ getSortData ~ flatData.value:',
      flatData.value
    );
    handleLevel();
    return Promise.resolve(res.positionCategoryList);
  } catch (error) {
    console.log(error);
  }
};

// 新增/编辑弹出框自定义事件
const typeEmit = async (formData: any | null) => {
  try {
    if (formData) {
      if (currStatus.value === 'add') {
        const data = {
          name: formData.name,
          remark: formData.remark,
          isEnable: formData.isEnable,
          code: formData.code,
          color: formData.color
        };
        if (formData.subSequenceName && formData.subSequenceName !== '') {
          data.name = formData.subSequenceName;
          data.pid = formData.id;
          data.code = '';
        } else if (formData.sequenceName && formData.sequenceName !== '') {
          data.name = formData.sequenceName;
          data.pid = formData.id;
          data.code = '';
        } else {
          data.name = formData.typeName;
        }
        await addPositionSortList(data);
        tableRef.value.loadData();
      } else if (currStatus.value === 'edit') {
        const data = formData;
        if (formData.subSequenceName && formData.subSequenceName !== '') {
          data.name = formData.subSequenceName;
        } else if (formData.sequenceName && formData.sequenceName !== '') {
          data.name = formData.sequenceName;
        } else {
          data.name = formData.typeName;
        }
        await setPositionSortList(data);
        tableRef.value.loadData();
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>
<style scoped lang="less">
.operation {
  display: flex;
  justify-content: flex-end;
  p {
    margin: 0 10px;
    color: #3d7eff;
    cursor: pointer;
  }
  p:last-child {
    color: red;
  }
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}

.icon {
  cursor: pointer;
  display: flex;
  justify-content: flex-start;
}
</style>
